<template>
	<a-card :bordered="false">
		<s-table
			ref="table"
			:columns="columns"
			:data="loadData"
			:expand-row-by-click="true"
			:showPagination="false"
			:row-key="(record) => record.id"
			bordered
		>
			<template #bodyCell="{ column, record }">
				<template v-if="column.dataIndex === 'fieldIndex'">
					<drag-outlined class="drag-btn" />
				</template>
				<template v-if="column.dataIndex === 'fieldRemark'">
					<a-input v-model:value="record.fieldRemark" />
				</template>
				<template v-if="column.dataIndex === 'width'">
					<a-input v-model:value="record.width" />
				</template>
				<template v-if="column.dataIndex === 'fieldNetType'">
					<a-select
						v-model:value="record.fieldNetType"
						:disabled="toCommonFieldEstimate(record)"
						:options="genConst.fieldNetTypeOptions"
						placeholder="请选择"
						style="width: 100%"
						@change="fieldNetTypeChange(record)"
					/>
				</template>
				<template v-if="column.dataIndex === 'effectType'">
					<a-select
						v-model:value="record.effectType"
						:disabled="toCommonFieldEstimate(record) || toFieldSelectEstimate(record)"
						:options="genConst.effectTypeOptions"
						@change="effectTypeChange(record, $event)"
						placeholder="请选择"
						style="width: 100%"
					/>
				</template>
				<template v-if="column.dataIndex === 'dictTypeCode'">
					<a-select
						v-if="record.effectType === 'radio' || record.effectType === 'select' || record.effectType === 'checkbox'"
						v-model:value="record.dictTypeCode"
						:options="dictTypeCodeOptions"
						placeholder="请选择字典"
						style="width: 100%"
					/>
					<span v-else>无</span>
				</template>
				<template v-if="column.dataIndex === 'whetherTable'">
					<a-checkbox v-model:checked="record.whetherTable" />
				</template>
				<template v-if="column.dataIndex === 'whetherRetract'">
					<a-checkbox v-model:checked="record.whetherRetract" :disabled="!record.whetherTable" />
				</template>
				<template v-if="column.dataIndex === 'whetherResizable'">
					<a-checkbox v-model:checked="record.whetherResizable" :disabled="!record.whetherTable" />
				</template>
				<template v-if="column.dataIndex === 'whetherAddUpdate'">
					<a-checkbox v-model:checked="record.whetherAddUpdate" :disabled="toFieldEstimate(record)" />
				</template>
				<template v-if="column.dataIndex === 'whetherImportExport'">
					<a-checkbox v-model:checked="record.whetherImportExport" :disabled="toFieldEstimate(record)" />
				</template>
				<template v-if="column.dataIndex === 'whetherRequired'">
					<a-checkbox
						v-model:checked="record.whetherRequired"
						:disabled="toFieldEstimate(record) || !record.whetherAddUpdate"
					/>
				</template>
				<template v-if="column.dataIndex === 'queryWhether'">
					<a-switch v-model:checked="record.queryWhether" :disabled="!record.whetherTable" />
				</template>
				<template v-if="column.dataIndex === 'queryType'">
					<a-select
						v-if="record.queryWhether === true && record.effectType !== 'datepicker'"
						v-model:value="record.queryType"
						:options="genConst.queryTypeOptions"
						placeholder="请选择"
						style="width: 100%"
					/>
					<span v-else-if="record.effectType === 'datepicker' && record.queryWhether === true">时间段</span>
					<span v-else>无</span>
				</template>
			</template>
		</s-table>
	</a-card>
	<FkForm ref="fkFormRef" @successful="table.refresh(true)" />
</template>

<script name="genConfig" setup>
	import tool from '@/utils/tool'
	import genConfigApi from '@/api/gen/genConfigApi'
	import { cloneDeep } from 'lodash-es'
	import * as genConst from './genConst'
	import Sortable from 'sortablejs'
	import FkForm from './fkForm.vue'

	const table = ref()
	const recordData = ref()
	const tableData = ref([])
	const fkFormRef = ref() //外键表单

	const columns = [
		{
			title: '排序',
			align: 'center',
			dataIndex: 'fieldIndex',
			width: 60
		},
		{
			title: '字段',
			align: 'center',
			dataIndex: 'fieldName',
			ellipsis: true
		},
		{
			title: '注释',
			align: 'center',
			dataIndex: 'fieldRemark',
			ellipsis: true
		},
		{
			title: '类型',
			align: 'center',
			dataIndex: 'fieldType',
			width: 100,
			ellipsis: true
		},
		{
			title: '实体类型',
			align: 'center',
			dataIndex: 'fieldNetType',
			ellipsis: true,
			width: 100
		},
		{
			title: '作用类型',
			align: 'center',
			dataIndex: 'effectType',
			ellipsis: true
		},
		{
			title: '字典',
			align: 'center',
			dataIndex: 'dictTypeCode',
			width: 140
		},
		{
			title: '列宽',
			align: 'center',
			dataIndex: 'width',
			width: 80
		},
		{
			title: '列表显示',
			align: 'center',
			dataIndex: 'whetherTable',
			width: 80
		},
		{
			title: '列省略',
			align: 'center',
			dataIndex: 'whetherRetract',
			width: 80
		},
		{
			title: '可伸缩列',
			align: 'center',
			dataIndex: 'whetherResizable',
			width: 80
		},
		{
			title: '增改',
			align: 'center',
			dataIndex: 'whetherAddUpdate',
			width: 80
		},
		{
			title: '导入导出',
			align: 'center',
			dataIndex: 'whetherImportExport',
			width: 80
		},
		{
			title: '必填',
			align: 'center',
			dataIndex: 'whetherRequired',
			width: 80
		},
		{
			title: '查询',
			align: 'center',
			dataIndex: 'queryWhether',
			width: 80
		},
		{
			title: '查询方式',
			align: 'center',
			dataIndex: 'queryType'
		}
	]
	const onOpen = (record) => {
		recordData.value = record
		nextTick(() => {
			table.value.refresh()
		})
	}
	// 表格查询 返回 Promise 对象
	const loadData = (parameter) => {
		if (recordData.value) {
			parameter.basicId = recordData.value.id
			return genConfigApi.configList(parameter).then((data) => {
				tableData.value = data
				tableData.value.forEach((item, index) => {
					for (const key in item) {
						if (item[key] === 'Y') {
							item[key] = true
						}
						if (item[key] === 'N') {
							item[key] = false
						}
					}

					// 去掉删除标识
					// 如果是主键，我们不提供主键的配置，也用不到
					if (
						item.isPrimarykey ||
						item.fieldName.toLowerCase().includes('isdelete') ||
						item.fieldName.toLowerCase().includes('createuserid') ||
						item.fieldName.toLowerCase().includes('updateuserid')
					) {
						tableData.value = tableData.value.filter((table) => {
							return table.fieldName != item.fieldName
						})
					}
					// 让默认的变成设置的
					fieldNetTypeChange(item)
				})

				return tableData.value
			})
		} else {
			return new Promise((resolve, reject) => {
				resolve([])
			})
		}
	}

	// 字典数据
	const dictTypeCodeOptions = tool.dictDataAll().map((item) => {
		return {
			label: item.dictLabel,
			value: item.dictValue
		}
	})

	const emit = defineEmits({ successful: null }, { close: null })
	const toFieldEstimate = (data) => {
		if (
			data.fieldName.toLowerCase().includes('createuser') ||
			data.fieldName.toLowerCase().includes('createtime') ||
			data.fieldName.toLowerCase().includes('updateuser') ||
			data.fieldName.toLowerCase().includes('updatetime') ||
			data.fieldName.toLowerCase().includes('isdelete') ||
			data.fieldName.toLowerCase().includes('createuserid') ||
			data.fieldName.toLowerCase().includes('updateuserid') ||
			data.isPrimarykey === true
		) {
			return true
		}
		return false
	}
	// 通用字段是否可选
	const toCommonFieldEstimate = (record) => {
		if (
			record.fieldName.toLowerCase().includes('createuser') ||
			record.fieldName.toLowerCase().includes('updateuser')
		) {
			return true
		}
		return false
	}
	// 设置该下拉框是否能选
	const toFieldSelectEstimate = (record) => {
		if (record.fieldNetType === 'DateTime' && record.effectType === 'datepicker') {
			return true
		}
		return false
	}
	// 实体类型选择触发
	const fieldNetTypeChange = (record) => {
		if (record.fieldNetType === 'DateTime') {
			record.effectType = 'datepicker'
		}
	}
	//改变作用类型
	const effectTypeChange = (record, value) => {
		if (value === 'fk') {
			fkFormRef.value.onOpen(record)
		} else {
			record.fkEntityName = ''
			record.fkColumnName = ''
			record.fkColumnId = ''
		}
	}

	// 提交
	const onSubmit = (recordData) => {
		let submitParam = cloneDeep(tableData.value)
		console.log(tableData.value)
		let errStatus = 100
		submitParam.forEach((item) => {
			// 必填那一项转换
			for (const key in item) {
				//不转isdeleste
				if (key != 'isDelete') {
					if (item[key] === true) {
						item[key] = 'Y'
					}
					if (item[key] === false) {
						item[key] = 'N'
					}
				}
			}
			if (item.queryWhether === 'Y' && !item.queryType) {
				// 排除掉时间选择
				if (item.fieldNetType !== 'DateTime' && item.effectType !== 'checkbox' && item.fieldNetType !== 'Date') {
					errStatus++
				}
			}
			if (
				(item.effectType === 'select' || item.effectType === 'radio' || item.effectType === 'checkbox') &&
				!item.dictTypeCode
			) {
				errStatus++
			}
		})
		return new Promise((resolve, reject) => {
			if (errStatus > 100) {
				reject('校验失败，请选择对应的下拉框选项')
				return
			}
			console.log(submitParam)
			genConfigApi
				.configEditBatch(submitParam)
				.then((data) => {
					resolve(data)
				})
				.catch((err) => {
					reject(err)
				})
		})
	}

	const rowDrop = () => {
		const $table = table.value

		const sortable = $table.$el.querySelector('.ant-table-tbody')
		// const sortable = document.querySelector('.ant-table-tbody') // 元素选择器名称根据实际内容替换
		Sortable.create(sortable, {
			handle: '.drag-btn',
			fillter: '.ant-table-measure-row',
			onEnd: (sortableEvent) => {
				let oldIndex = sortableEvent.oldIndex
				let newIndex = sortableEvent.newIndex
				if (oldIndex != newIndex) {
					let editList = []
					//向后移动
					if (oldIndex < newIndex) {
						let old = tableData.value[oldIndex]
						let m = tableData.value[newIndex].fieldIndex
						let rm = old.fieldIndex
						//中间项前移
						for (let i = oldIndex; i < newIndex; i++) {
							let trm = rm
							rm = tableData.value[i + 1].fieldIndex
							tableData.value[i + 1].fieldIndex = trm
							editList.push(tableData.value[i + 1])
							tableData.value[i] = tableData.value[i + 1]
						}
						old.fieldIndex = m
						editList.push(old)
						tableData.value[newIndex] = old
					}
					//向前移动
					else {
						let old = tableData.value[oldIndex]
						let m = tableData.value[newIndex].fieldIndex
						let rm = old.fieldIndex
						//中间项后移
						for (let i = oldIndex; i > newIndex; i--) {
							let trm = rm
							rm = tableData.value[i - 1].fieldIndex
							tableData.value[i - 1].fieldIndex = trm
							editList.push(tableData.value[i - 1])
							tableData.value[i] = tableData.value[i - 1]
						}
						old.fieldIndex = m
						editList.push(old)
						tableData.value[newIndex] = old
					}
				}
			}
		})
	}

	onMounted(() => {
		nextTick(() => rowDrop())
	})
	// 抛出钩子
	defineExpose({
		onOpen,
		onSubmit
	})
</script>
<style scoped>
	.table-wrapper {
		margin-top: -16px !important;
	}
</style>
